<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.amazon_us_post_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="主ASIN" prop="mainAsin">
        <el-input
          v-model="queryParams.mainAsin"
          placeholder="请输入主ASIN"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="店铺" prop="shop">
        <el-select v-model="queryParams.shop" placeholder="请选择店铺" clearable>
          <el-option
            v-for="dict in dict.type.amazon_us_shop_list"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-select v-model="queryParams.brand" placeholder="请选择品牌" clearable>
          <el-option
            v-for="dict in dict.type.brand_list"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="修改者" prop="updateBy">
        <el-select v-model="queryParams.updateBy" placeholder="请选择修改者" clearable>
          <el-option
            v-for="dict in dict.type.update_by_name_list"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="排序方式">
        <el-select v-model="sortForm.sort" placeholder="请选择排序方式" @change="handleSortChange">
          <el-option label="按ID升序" value="id,asc"></el-option>
          <el-option label="按ID降序" value="id,desc"></el-option>
          <el-option label="按修改时间升序" value="updateTime,asc"></el-option>
          <el-option label="按修改时间降序" value="updateTime,desc"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['amazon_us:post:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['amazon_us:post:edit']"
        >修改</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['amazon_us:post:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['amazon_us:post:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" width="120" align="center" prop="id" />
      <el-table-column label="状态" width="120" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.amazon_us_post_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="主ASIN" width="120" align="center" prop="mainAsin" />
      <el-table-column label="副ASIN" width="360" show-overflow-tooltip="true" align="center" prop="otherAsin" />
      <el-table-column label="图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="文案" width="360" show-overflow-tooltip="true" align="center" prop="caption" />
      <el-table-column label="店铺" width="120" align="center" prop="shop">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.amazon_us_shop_list" :value="scope.row.shop"/>
        </template>
      </el-table-column>
      <el-table-column label="品牌" width="120" align="center" prop="brand">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.brand_list" :value="scope.row.brand"/>
        </template>
      </el-table-column>
      <el-table-column label=" 修改者" align="center" prop="updateBy">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.update_by_name_list" :value="scope.row.updateBy"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" width="220" show-overflow-tooltip="true"  align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['amazon_us:post:edit']"
          >修改</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['amazon_us:post:remove']"-->
<!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <BackToTop />
    <BackToBottom/>
    <!-- 添加或修改上传POST对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="添加POST不要选">
            <el-option
              v-for="dict in dict.type.amazon_us_post_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="店铺(可选)" prop="shop">
          <el-select v-model="form.shop" placeholder="请选择店铺">
            <el-option
              v-for="dict in dict.type.amazon_us_shop_list"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主ASIN" prop="mainAsin">
          <el-input v-model="form.mainAsin" placeholder="请输入主ASIN" @blur="handleMainAsinBlur" />
        </el-form-item>
        <el-form-item label="副ASIN" prop="otherAsin">
          <el-input v-model="form.otherAsin" placeholder="请输入副ASIN,最多四个,请用英文半角逗号分割ASIN" />
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <image-preview width="100px" height="100px" :src="form.image"/>
          <el-input v-model="form.image" type="input" placeholder=""/>
          <div v-if="imageLoading" class="image-loading">
            <i class="el-icon-loading"></i> 正在加载图片...
          </div>
          <div v-else-if="imageList.length > 0" class="image-list">
            <div
              v-for="(img, index) in imageList"
              :key="index"
              class="image-item"
              :class="{'image-item-selected': img === selectedImageUrl}"
              @click="selectImage(img)"
            >
              <image-preview width="80px" height="80px" :src="img" />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="文案" prop="caption">
          <el-input v-model="form.caption" type="textarea" placeholder="若该主ASIN非机器上架的,也需要发Post请手动填写文案,否则别填." />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPost, getPost, delPost, addPost, updatePost, getImagesByMainAsin } from "@/api/amazon_us/post";
import globalMixins from '@/utils/globalMixins'

export default {
  name: "Post",
  dicts: ['amazon_us_shop_list', 'brand_list', 'amazon_us_post_status','update_by_name_list'],
  data() {
    return {
      pickerOptions: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 上传POST表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeCreateTime: [],
      // 查询参数
      sortForm: {
        sort: 'id,desc' // 默认值
      },
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        status: null,
        mainAsin: null,
        shop: null,
        brand: null,
        updateBy: null,
        createTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        mainAsin: [
          { required: true, message: "主ASIN不能为空", trigger: "blur" }
        ],
        image: [
          { required: true, message: "请选择图片"}
        ],

      },
      imageList: [],
      imageLoading: false, // 图片加载状态
      selectedImageUrl: '' // 当前选中的图片URL
    };
  },
  created() {
    this.pickerOptions = globalMixins.data().pickerOptions
    this.$set(this.queryParams, 'orderByColumn', 'id');
    this.$set(this.queryParams, 'isAsc', 'desc');
    this.getList();
  },
  methods: {
    /** 查询上传POST列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listPost(this.queryParams).then(response => {
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        status: null,
        mainAsin: null,
        otherAsin: null,
        image: null,
        caption: null,
        shop: null,
        brand: null,
        updateBy: null,
        remark: null,
        createTime: null,
        updateTime: null
      };
      this.imageList = []; // 清空图片列表
      this.selectedImageUrl = ''; // 清空选中的图片
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加上传POST";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPost(id).then(response => {
        this.form = response.data;
        this.selectedImageUrl = this.form.image; // 设置当前选中的图片
        this.open = true;
        this.title = "修改上传POST";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePost(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPost(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除上传POST编号为"' + ids + '"的数据项？').then(function() {
        return delPost(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('amazon_us/post/export', {
        ...this.queryParams
      }, `post_${new Date().getTime()}.xlsx`)
    },
    /** 主ASIN输入框失去焦点时触发 */
    handleMainAsinBlur() {
      if (this.form.mainAsin && this.form.mainAsin.trim() !== '') {
        // 清空之前的图片列表
        this.imageList = [];
        // 显示加载中
        this.imageLoading = true;
        // 调用API获取图片列表
        getImagesByMainAsin(this.form.mainAsin).then(response => {
          if (response.code === 200 && response.data) {
            this.imageList = response.data;
          } else {
            this.$message.warning('未找到相关图片');
          }
          this.imageLoading = false;
        }).catch(() => {
          // this.$message.error('获取图片列表失败');
          this.imageLoading = false;
        });
      }
    },
    /** 选择图片 */
    selectImage(image) {
      this.form.image = image;
      this.selectedImageUrl = image;
      this.$message.success('已选择图片');
    }
  }
};
</script>

<style scoped>
.image-list {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
  gap: 10px;
}
.image-item {
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 5px;
  transition: all 0.3s;
}
.image-item:hover {
  border-color: #409eff;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
}
.image-loading {
  margin-top: 10px;
  color: #909399;
  font-size: 14px;
}
.image-item-selected {
  border: 2px solid #409eff;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.5);
  position: relative;
}
.image-item-selected::after {
  content: "✓";
  position: absolute;
  top: 5px;
  right: 5px;
  width: 20px;
  height: 20px;
  background-color: #409eff;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}
</style>
